package com.xingguo.account;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.base.component.BaseAction;
import com.base.component.BaseHibernateDAO;
import com.base.component.Constant;
import com.base.component.MessageConstant;
import com.base.component.Pager;
import com.opensymphony.xwork2.ModelDriven;

@Controller
public class AccountAction extends BaseAction implements ModelDriven<Account> {
	@Resource
	BaseHibernateDAO baseHibernateDAO;

	private Pager pager = new Pager();
	private Integer currentId;
	private String newPassword;
	private String[] idArray;

	public Account account = new Account();
	static Logger logger = LogManager.getLogger(AccountAction.class.getName());

	@Override
	public Account getModel() {
		return account;
	}

	@SuppressWarnings("unchecked")
	public String login() {
		HttpSession session = getRequest().getSession();
		if(session.getAttribute(Constant.ACCOUNT_ID) != null){
			return redirect(Constant.PAGE_ADMIN);
		}
		List<Account> list = baseHibernateDAO.findByProperty(Account.class, new String[] { "name","password" },
				new Object[] { account.getName(), account.getPassword() }, 0, 10);
		if(list.size() == 0){
			return addAttr(Constant.MSG_ERROR, "用户名或者密码错误，请核对后重试").forward(Constant.PAGE_LOGIN);
		}
		Account  user= list.get(0);
		session.setAttribute(Constant.ACCOUNT_ID,user.getId());
		session.setAttribute(Constant.ACCOUNT_NAME,user.getName());
		logger.info("login:{}",user);
		return redirect(Constant.PAGE_ADMIN);
	}

	public String logout() {
		HttpSession session = getRequest().getSession();
		logger.info("logout:{},{}",session.getAttribute(Constant.ACCOUNT_ID),session.getAttribute(Constant.ACCOUNT_NAME));
		session.invalidate();
		return redirect(Constant.PAGE_LOGIN);
	}

	public String changePassword(){
		HttpSession session = getRequest().getSession();
		Integer currentAccountId = (Integer) session.getAttribute(Constant.ACCOUNT_ID);
		Account currentAccount = (Account) baseHibernateDAO.get(Account.class, currentAccountId);
		String oldPassword = account.getPassword();
		if(oldPassword.equals(currentAccount.getPassword())){
			currentAccount.setPassword(newPassword);
			getRequest().setAttribute(Constant.MESSAGE, MessageConstant.EDIT_SUCCESS);
			return forward("success.jsp");
		}
		else{
			
			return addAttr(Constant.MSG_ERROR, "初始密码输入错误").error("password.jsp");
		}
	}
	
	public String goToAdd() {
		Account newAccount = new Account();
		return addAttr("newAccount", newAccount).forward("add.jsp");
	}

	public String add() {
		String newUsername = account.getUsername();
		String hql = "select count(*) from Account a where a.username = '"+newUsername+"'";
		Long count = baseHibernateDAO.countByHQL(hql);
		if(count>0){
			addAttr(Constant.MSG_ERROR, "用户名已存在");
			return forward("add.jsp");
		}
		account.setRegDate(new Date());
		baseHibernateDAO.save(account);
		logger.info("add:{}", account);
		addAttr(Constant.MESSAGE, MessageConstant.SAVE_SUCCESS);
		return forward("success.jsp");
	}

	private HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	public String goToEdit() {
		Account editaccount = (Account) baseHibernateDAO.get(Account.class,
				currentId);
		return addAttr("editaccount", editaccount).forward("edit.jsp");
	}

	public String edit() {
		baseHibernateDAO.update(account);
		logger.info("edit:{}",account);
		addAttr(Constant.MESSAGE, MessageConstant.EDIT_SUCCESS);
		return search();
	}

	public String delete() {
		baseHibernateDAO.delete(account);
		logger.info("delete:{}",account);
		addAttr(Constant.MESSAGE, MessageConstant.DELETE_SUCCESS);
		return search();
	}
	public String deleteBatch(){
		baseHibernateDAO.deleteBatch(Account.class, idArray);
		logger.info("deleteBatch:{}",(Object[])idArray);
		addAttr(Constant.MESSAGE, MessageConstant.DELETE_SUCCESS);
		return search();
	}

	@SuppressWarnings("unchecked")
	public String list() {
		System.out.println(pager);
		Long totalSize = baseHibernateDAO.count(Account.class);
		pager.setTotalSize(totalSize);
		int offSet = pager.getOffset();
		int pageSize = pager.getSize();
		List<Account> list = baseHibernateDAO.query(Account.class, offSet,
				pageSize);
		logger.debug(list);
		return addAttr("list", list).forward("list.jsp");
	}

	@SuppressWarnings("unchecked")
	public String search(){
		String name = "";
		name = pager.getValues()[0];
		String hql = "from Account a where a.username like '%"+name+"%' or a.name like '%"+name+"%'";
		pager.setProps(new String[]{"username"});
		Long totalSize = baseHibernateDAO.countByHQL("select count(*)"+hql);
		pager.setTotalSize(totalSize);
		int offSet = pager.getOffset();
		int pageSize = pager.getSize();
		List<Account> list = baseHibernateDAO.findByHQL(hql, offSet, pageSize);
		return addAttr("list", list).forward("list.jsp");
	} 
	
	public Pager getPager() {
		return pager;
	}

	public void setPager(Pager pager) {
		this.pager = pager;
	}

	public Integer getCurrentId() {
		return currentId;
	}

	public void setCurrentId(Integer currentId) {
		this.currentId = currentId;
	}

	public String[] getIdArray() {
		return idArray;
	}

	public void setIdArray(String[] idArray) {
		this.idArray = idArray;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}
}
